import informationPick from "@/components/InformationPick/information-pick.vue";
import { createApp, h } from "vue";
function MeasureDuanmianVer({ map, overlayLimit = 1, mittBus, type }) {
  const ins = MeasureDuanmianVer.getIns();
  if (ins) {
    return ins
  }
  this.map = map;
  this.mittBus = mittBus;
  this.type = type;
  this.listenerClick = null;
  this.listenerMove = null;
  this.overlayLimit = overlayLimit;
  this.overlaysArr = [];
  this.sourceVec = null;
  this.layerPoint = null;
  this.styleVec = null;
  this.init();
  MeasureDuanmianVer.ins = this;
}
MeasureDuanmianVer.getIns = function () {
  return MeasureDuanmianVer.ins;
}
MeasureDuanmianVer.create = function ({ map, overlayLimit, mittBus, type }) {
  return new MeasureDuanmianVer({ map, overlayLimit, mittBus, type })
}
function resetStyleSelf(n) {
  const s_ = new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(20, 255, 34, 1)',
      width: 5,
      lineDash: [10, 5],
      lineDashOffset: n,
      lineCap: 'butt'
    }),
    fill: new ol.style.Fill({
      color: 'rgba(20, 255, 34, 0.5)',
      width: 5
    })
  });
  return s_;
}
// 初始化
MeasureDuanmianVer.prototype.init = function () {
  if (!ol) { return }
  if (!this.map) { return }
  // 矢量数据源
  this.sourceVec = new ol.source.Vector();
  this.layerPoint = new ol.layer.Vector({
    source: this.sourceVec
  });
  // 矢量样式
  this.styleVec = new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'rgba(20, 255, 34, 1)',
      width: 5,
      lineDash: [5, 10],
      lineDashOffset: 0
    }),
    fill: new ol.style.Fill({
      color: 'rgba(20, 255, 34, 0.5)',
      width: 5
    })
  });
  this.layerPoint.setZIndex(21);
  this.map.addLayer(this.layerPoint);

  // 初始化绑定事件
  this.bindEvt();
}
// 绑定事件
MeasureDuanmianVer.prototype.bindEvt = function () {
  // this.map.getViewport().style.cursor = 'pointer';
  const this_ = this;
  let pixel, hit;
  this.listenerMove = this.map.on('pointermove', (e) => {
    pixel = this_.map.getEventPixel(e.originalEvent);
    hit = this_.map.hasFeatureAtPixel(pixel);
    if (pixel && hit) {
      this_.map.getTargetElement().style.cursor = 'pointer';
    } else {
      this_.map.getTargetElement().style.cursor = '';
    }
  });
  this.listenerClick = this.map.on('click', (e) => {
    const feature = this.map.forEachFeatureAtPixel(e.pixel, function (feature) {
      return feature;
    }, {
      hitTolerance: 0
    });
    if (pixel && hit && feature) {
      this.putOverlay(e, feature.getProperties() || {});
    }
  })
}
// 添加overlay
MeasureDuanmianVer.prototype.putOverlay = function (e, attr) {
  if (attr.layerType !== "LINE" && attr.layertype !== "LINE") {
    return
  }
  if (this.overlaysArr.length >= this.overlayLimit) {
    const head = this.overlaysArr[0];
    this.clearSingleOverlay(head);
    this.overlaysArr.shift();
  }
  const coordinate = e.coordinate;
  if (!coordinate) { return }
  const [longitude, latitude] = coordinate;
  if (!longitude || !latitude) { return }
  const unid = new Date().getTime()
  const attrIns = this;
  let simpleData = [];
  let additionData = [];
  // const showAttr = window.SUPER_GIS_SPACE.setting[attr.GXXZ][attr.layerType]["SIMPLE"]
  // 小类型
  const type_ = window.SUPER_GIS_SPACE.setting[attr.gxxz || attr.GXXZ];
  if (!type_) { return }
  // 线 点
  const type_s = type_[attr.layertype || attr.layerType]
  if (!type_s) { return }
  // 简单属性
  const simple_ = type_s['SIMPLE'];
  if (!simple_) { return }
  // 附加类型
  const addition_ = type_s['ADDTION'];
  if (simple_) {
    simple_.forEach(v => {
      simpleData.push({
        key: v,
        value: attr[v]
      })
    })
  }
  if (addition_) {
    addition_.forEach(v => {
      additionData.push({
        key: v,
        value: attr[v]
      })
    })
  }
  const app = createApp({
    render() {
      return h(informationPick, {
        mainTitle: '管线管点·属性',
        simpleData: simpleData,
        additionData: additionData,
        isMiniProp: true,
        unid,
        onClose: (e) => {
          const { unid } = e;
          for (let i = 0; i < attrIns.overlaysArr.length; i++) {
            const item = attrIns.overlaysArr[i];
            if (item.id === unid) {
              attrIns.clearSingleOverlay(item);
              attrIns.overlaysArr.splice(i, 1);
              break;
            }
          }
        }
      })
    }
  })
  // 暂时不用
  // app.onUnmount()
  const parent = document.createElement('div');
  const el = app.mount(parent).$el;
  // 创建Overlay
  const overlay = new ol.Overlay({
    id: unid,
    element: el,
    offset: [0, -15],
    positioning: 'bottom-center',
    insertFirst: false,
    stopEvent: true
  });
  let featureVector;
  let intervalId;
  let intervalIdObj = {};
  if (attr
    && (attr.layerType === "LINE" || attr.layertype === "LINE")
    && attr.endx && attr.endy && attr.startx && attr.startx
  ) {
    featureVector = new ol.Feature({
      geometry: new ol.geom.LineString([
        [attr.endx, attr.endy],
        [attr.startx, attr.starty]
      ])
    });
    featureVector.setStyle(this.styleVec);
    this.sourceVec.addFeature(featureVector);
    let lineN = 0;
    function fun_() {
      intervalIdObj.id = requestAnimationFrame(fun_);
      let s = resetStyleSelf(lineN++);
      if (lineN > 150) { lineN = 0 };
      featureVector.setStyle(s);
    }
    fun_();
    // intervalId = setInterval(() => {
    //   let s = resetStyleSelf(lineN++);
    //   if(lineN > 150) { lineN = 0};
    //   featureVector.setStyle(s);
    //   console.log(111)
    // }, 20)
  }

  this.map.addOverlay(overlay); // 将Overlay添加到地图
  overlay.setPosition(coordinate); // 设置Overlay的位置
  this.overlaysArr.push({
    id: unid,
    app,
    overlay,
    featureVector,
    intervalId,
    intervalIdObj,
    attr
  });
  // if (this.overlaysArr.length === this.overlayLimit) {}
  this.mittBus && this.mittBus.emit(this.type, {
    data: this.overlaysArr.map(v => v.attr)
  })
}
// 清除单个
MeasureDuanmianVer.prototype.clearSingleOverlay = function (item) {
  item.app.unmount();
  this.map.removeOverlay(item.overlay);
  this.sourceVec.removeFeature(item.featureVector);
  // clearInterval(item.intervalId);
  cancelAnimationFrame(item.intervalIdObj.id);
}
// 清除所有
MeasureDuanmianVer.prototype.clearAllOverlay = function () {
  const arr = this.overlaysArr;
  if (arr.length) {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      this.clearSingleOverlay(item);
    }
    this.overlaysArr = [];
  }
}
// 销毁实例
MeasureDuanmianVer.prototype.destroy = function () {
  ol.Observable.unByKey(this.listenerClick);
  ol.Observable.unByKey(this.listenerMove);
  this.listenerClick = null;
  this.listenerMove = null;
  this.clearAllOverlay();
  this.mittBus && this.mittBus.all.clear();
  MeasureDuanmianVer.ins = null;
  this.map.getViewport().style.cursor = 'inherit';
}
export default MeasureDuanmianVer